package helpers;

import java.util.ArrayList;
import java.util.Date;

import models.AutoSite;
import models.MessageQueue;
import data.AutoSiteData;
import data.MessageQueueData;

public class CronHelper {
	public static ArrayList<String> cronLastestNews(String siteId) {
		AutoSite autoSite = AutoSiteData.getById(siteId);
		
		//Get lastest news
		ArrayList<String> lastestNews = CrawlerHelper.getLastestNews(autoSite);
		MessageQueue messageQueue = new MessageQueue();
		
		for (int i = 0; i < lastestNews.size(); i++) {
			messageQueue = new MessageQueue();
			messageQueue.setAutoSiteId(autoSite.getId());
			messageQueue.setUrl(lastestNews.get(i));
			messageQueue.setId(messageQueue.createId());
			messageQueue.setIsDone(false);
			if (MessageQueueData.getById(messageQueue.getId()) == null) {
				MessageQueueData.insert(messageQueue);
			}
		}
		
		return lastestNews;
	}
	
	public static ArrayList<String> cronPageNews(String siteId) {
		AutoSite autoSite = AutoSiteData.getById(siteId);
		//Get page news
		ArrayList<String> pageNews = CrawlerHelper.getPageNews(autoSite);
		
		//Increate page news and save data
		autoSite.setLastestScheduleSitePage(new Date());
		autoSite.setCurrentPage(autoSite.getCurrentPage() + 1);
		AutoSiteData.insert(autoSite);
		//Get list news
		MessageQueue messageQueue = new MessageQueue();
		
		for (int i = 0; i < pageNews.size(); i++) {
			messageQueue = new MessageQueue();
			messageQueue.setAutoSiteId(autoSite.getId());
			messageQueue.setUrl(pageNews.get(i));
			messageQueue.setId(messageQueue.createId());
			messageQueue.setIsDone(false);
			
			if (MessageQueueData.getById(messageQueue.getId()) == null) {
				System.out.println(messageQueue.getId());
				System.out.println(messageQueue.getUrl());
				MessageQueueData.insert(messageQueue);
			}
		}
		
		return pageNews;
	}
}
